package org.xlx.xlx_oa.role_user.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.unit.DataSize;
import org.springframework.web.multipart.MultipartFile;
import org.xlx.xlx_oa.common.Constant;
import org.xlx.xlx_oa.common.PageVo;
import org.xlx.xlx_oa.role_user.convertor.RoleUserConvertor;
import org.xlx.xlx_oa.role_user.domain.SysNotification;
import org.xlx.xlx_oa.role_user.domain.dto.SysNotificationDto;
import org.xlx.xlx_oa.role_user.mapper.SysNotificationMapper;
import org.xlx.xlx_oa.utils.ThreadLocalUtil;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

@Service
public class SysNotificationService {
    private final RoleUserConvertor roleUserConvertor = RoleUserConvertor.INSTANCE;
    @Autowired
    private SysNotificationMapper sysNotificationMapper;

    @Value("${spring.servlet.multipart.max-file-size:3MB}")
    private DataSize maxFileSize;

    /**
     * 上传图片
     *
     * @param file
     * @return src图片显示路径
     * @throws Exception
     */
    public String upload(MultipartFile file) throws Exception {
        if (file.getSize() > maxFileSize.toBytes()) {
            throw new Exception("file too large");
        }
        InputStream inputStream = file.getInputStream();
        String relativePath = null;
        //判断上传文件格式
        String fileType = file.getContentType();
        if (fileType.equals("image/jpeg") || fileType.equals("image/png") || fileType.equals("image/jpg")) {
            // 要上传的目标文件存放的绝对路径
            Object obj = ThreadLocalUtil.get(Constant.USERID);
            Long userId = Objects.isNull(obj) ? null : Long.valueOf(obj.toString());
            final String localPath = Constant.ICON_LOCATION + "/" + userId;
            File imageDict = new File(localPath);
            if (!imageDict.exists()) {
                imageDict.mkdirs();
            }
            //上传后保存的文件名(需要防止图片重名导致的文件覆盖)
            //获取文件名
            String fileName = file.getOriginalFilename();
            //获取文件后缀名
            assert fileName != null;
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            //重新生成文件名
            fileName = UUID.randomUUID() + suffixName;
            if (this.uploadValidate(file, localPath, fileName)) {
                relativePath = userId + "/" + fileName;
            } else {
                throw new Exception("file upload failed");
            }
        } else {
            throw new Exception("file type error");
        }
        return relativePath;
    }

    public boolean uploadValidate(MultipartFile file, String path, String fileName) {

        //确定上传的文件名
        String realPath = path + "\\" + fileName;
        File dest = new File(realPath);

        //判断文件父目录是否存在
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }

        try {
            //保存文件
            file.transferTo(dest);
            return true;
        } catch (IllegalStateException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 获取当前用户的通知信息
     *
     * @param pageVo
     * @return
     */
    public List<SysNotificationDto> selectNotificationsByUserId(PageVo pageVo) {
        Integer pageNum = pageVo.getPageNum();
        Integer pageSize = pageVo.getPageSize();
        Object obj = ThreadLocalUtil.get(Constant.USERID);
        Long userId = Objects.isNull(obj) ? null : Long.valueOf(obj.toString());
        Page<SysNotification> page = new Page<>(pageNum, pageSize);
        QueryWrapper<SysNotification> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(SysNotification::getUserId, userId)
                .orderByDesc(SysNotification::getCreatedDateTime);
        sysNotificationMapper.selectPage(page, wrapper);
        List<SysNotificationDto> dtos = roleUserConvertor.convertToListSysNotificationDto(page.getRecords());
        return dtos;
    }

    /**
     * 获取当前用户通知信息总数
     *
     * @return
     */
    public Integer getCount() {
        Object obj = ThreadLocalUtil.get(Constant.USERID);
        Long userId = Objects.isNull(obj) ? null : Long.valueOf(obj.toString());
        QueryWrapper<SysNotification> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(SysNotification::getUserId, userId);
        return sysNotificationMapper.selectCount(wrapper);
    }

    /**
     * 创建通知信息
     *
     * @param content 通知内容
     * @param userId  通知人id
     * @return
     */
    public Boolean createNotification(String content, Long userId) {
        SysNotification sysNotification = new SysNotification();
        sysNotification.setContent(content);
        sysNotification.setUserId(userId);
        return sysNotificationMapper.insert(sysNotification) > 0;
    }
}
